package com.dpndeveloper.snippets.classloader;

import java.io.File;
import java.io.FileFilter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Domenico Pio Novelli
 * 
 */
public class ClassLoaderUtil {

	/**
	 * Return a class loader that contains all jar library in the given folder
	 * 
	 * @param folder
	 *            folder that contains jar library
	 * @return Classloader the created classloader
	 */
	public static ClassLoader createJarClassLoader(File folder) {
		if (folder.exists() && folder.isDirectory()) {
			java.io.FileFilter fileFilter = new FileFilter() {

				@Override
				public boolean accept(File pathname) {
					return pathname.isFile()
							&& pathname.getName().toLowerCase()
									.endsWith(".jar");
				}
			};

			List<URL> urls = new ArrayList<URL>();
			for (File file : folder.listFiles(fileFilter)) {
				try {
					urls.add(new URL("file:///" + file.getAbsolutePath()));
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}
			}

			final ClassLoader current = Thread.currentThread()
					.getContextClassLoader();
			return new URLClassLoader(urls.toArray(new URL[urls.size()]),
					current) {

				@Override
				public Class loadClass(String name)
						throws ClassNotFoundException {
					try {
						Class rez = super.findClass(name);
						return rez;
					} catch (ClassNotFoundException c) {
						return super.loadClass(name, true);
					}
				}

			};
		}
		return null;
	}
}
